package org.wxd.media.engine;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wxd.media.api.MediaService;
import org.wxd.media.api.record.MediaRecord;
import org.wxd.media.api.record.MediaUploadRequest;
import org.wxd.media.domain.Media;
import org.wxd.media.domain.MediaOperations;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * Created by wangxd on 2016/11/1.
 */
@Service
@Transactional
public class MediaServiceImpl implements MediaService {

    @Resource
    MediaOperations ops;


    @Override
    public MediaRecord upload(MediaUploadRequest request) {
        Optional opt = ops.ofCheckSum(request.checksum());
        if (opt.isPresent()) return MediaHelper.asRecord((Media) opt.get());
        return MediaHelper.asRecord(ops.store(
                request.stream(), Media.newBuilder()
                        .moreInfo(request.moreInfo())
                        .suffix(request.name().substring(request.name().lastIndexOf(".")))
                        .name(request.name())
                        .contentType(request.contentType())
                        .expireTime(request.expireMillis())
                        .build()
        ));
    }


}
